package com.gxsyh.nantie.order.consumer.controller;

import com.gxsyh.nantie.commons.dto.ResponseResult;
import com.gxsyh.nantie.order.consumer.controller.dto.SubsidyInfoDTO;
import com.gxsyh.nantie.order.provider.TbDepartmentOrderService;
import com.gxsyh.nantie.order.provider.TbDepartmentService;
import com.gxsyh.nantie.order.provider.TbSubsidyService;
import com.gxsyh.nantie.order.provider.domain.TbDepartment;
import com.gxsyh.nantie.order.provider.domain.TbSubsidy;
import org.apache.dubbo.config.annotation.Reference;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @email yom535@outlook.com
 * @author: 有民(yom535)
 * @date: 2020/2/10
 * @time: 18:22
 * 订单生成
 */
@RestController
public class GenerateOrdersController {

    @Reference(version = "1.0.0")
    TbDepartmentService tbDepartmentService;

    @Reference(version = "1.0.0")
    TbSubsidyService tbSubsidyService;



    @Resource
    RedissonClient redissonClient;


    /**
     * 支付前获取餐补信息
     * @param departmentid 公寓ID
     * @return 返回是当前时间段的餐补，并且使用次数小于管理员设置的次数的餐补信息
     */
    @GetMapping(value = "/order/subsidy/info")
    public ResponseResult<SubsidyInfoDTO> subsidyInfo(@RequestParam Long departmentid)
    {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        //查询公寓信息
        TbDepartment tbDepartment = tbDepartmentService.selectOneByDepartmentId(departmentid);
        //查询当前时段的餐补信息
        List<TbSubsidy> nowTimeSubsidies=new ArrayList<>();

        //查询访问用户的部门ID并查询该单位下的所有餐补信息
        TbDepartment selectOneByUserId = tbDepartmentService.selectOneByUserId(Long.valueOf(authentication.getName()));
        //参数是用户的所属部门
        List<TbSubsidy> tbSubsidies = tbSubsidyService.selectSubsidyByDepartment(selectOneByUserId.getId());
        for (int i=0;i<tbSubsidies.size();i++)
        {
            boolean result = thinkTime(tbSubsidies.get(i).getStartime(), tbSubsidies.get(i).getEndtime());
            if (result)
            {
                nowTimeSubsidies.add(tbSubsidies.get(i));
            }
        }
//        tbSubsidies.forEach(tbSubsidy -> {
//            boolean result = thinkTime(tbSubsidy.getStartime(), tbSubsidy.getEndtime());
//            if (result)
//            {
//                nowTimeSubsidies.add(tbSubsidy);
//            }
//        });
        //查询次数
        List<TbSubsidy> nowSubsidies=new ArrayList<>();
        for (int i=0;i<nowTimeSubsidies.size();i++){
            RAtomicLong atomicLong = redissonClient.getAtomicLong(authentication.getName() + "_subsidyInfo_" + nowTimeSubsidies.get(i).getId());
            long res = atomicLong.get();
            if (res<Long.valueOf(nowTimeSubsidies.get(i).getNumberSubsidies())){
                nowSubsidies.add(nowTimeSubsidies.get(i));
            }
        }
//        nowTimeSubsidies.forEach(nowTimeSubsidie ->{
//            RAtomicLong atomicLong = redissonClient.getAtomicLong(authentication.getName() + "_subsidyInfo_" + nowTimeSubsidie);
//            long res = atomicLong.get();
//            if (res<Long.valueOf(nowTimeSubsidie.getNumberSubsidies())){
//                nowSubsidies.add(nowTimeSubsidie);
//            }
//        });

        //返回是当前时间段的餐补，并且使用次数小于管理员设置的次数的餐补信息
        SubsidyInfoDTO subsidyInfoDTO=new SubsidyInfoDTO();
        subsidyInfoDTO.setDepartmentName(tbDepartment.getName());
        subsidyInfoDTO.setSubsidy(nowSubsidies);
        return new ResponseResult<>(HttpStatus.OK.value(),"查询餐补成功",subsidyInfoDTO);
    }

    /**
     *      * 判断时间是否在时间段内
     *      * @param nowTime  当前时间
     *      * @param beginTime  开始时间
     *      * @param endTime   结束时间
     *      * @return
     *      
     */
    public static boolean thinkTime(String beginTimes, String endTimes) {

        if ("00:00".equals(beginTimes)&& "00:00".equals(endTimes))
        {
            return true;
        }

        int beginT = Integer.parseInt(beginTimes.substring(0, 2));
        int endT = Integer.parseInt(endTimes.substring(0,2));
        if (beginT>endT)
        {
            java.util.Calendar cal=java.util.Calendar.getInstance();
            cal.setTime(new Date());
            cal.add(Calendar.DATE,1);
            Date nextDate=cal.getTime();
            String next_dateStr = new SimpleDateFormat("yyyy-MM-dd").format(nextDate);
            StringBuilder sb = new StringBuilder();
            sb.append(next_dateStr);
            sb.append(" "+endTimes);

            SimpleDateFormat ends = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
            //初始化
            Date nowTime = null;
            Date beginTime = null;
            Date endTime = null;
            try {
                //格式化当前时间格式
                nowTime = df.parse(df.format(new Date()));
                //定义开始时间
                beginTime = df.parse(beginTimes);
                //定义结束时间
                endTime = ends.parse(sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            //用判断方法
            boolean flag = belongCalendar(nowTime, beginTime, endTime);
            //输出为结果
            if (flag) {
                //处于规定的时间段内，执行对应的逻辑代码
                return flag;
            } else {
                //不处于规定的时间段内，执行对应的逻辑代码
                return flag;

            }
        }

        SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
//初始化
        Date nowTime = null;
        Date beginTime = null;
        Date endTime = null;
        try {
            //格式化当前时间格式
            nowTime = df.parse(df.format(new Date()));
            //定义开始时间
            beginTime = df.parse(beginTimes);
            //定义结束时间
            endTime = df.parse(endTimes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //用判断方法
        boolean flag = belongCalendar(nowTime, beginTime, endTime);
        //输出为结果
        if (flag) {
            //处于规定的时间段内，执行对应的逻辑代码
            return flag;
        } else {
            //不处于规定的时间段内，执行对应的逻辑代码
            return flag;

        }
    }
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        //设置当前时间
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        //设置开始时间
        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);
        //设置结束时间
        Calendar end = Calendar.getInstance();
        end.setTime(endTime);
        //处于开始时间之后，和结束时间之前的判断
        return date.after(begin) && date.before(end);
    }
}
